#! /usr/bin/evn python
# coding:utf-8

from data import DB
from pycalendar import *
import uuid
import  datetime,time
import xlwt

class QComboBox(QComboBox):

    def wheelEvent(self, QWheelEvent):
        pass

class QDateTimeEdit(QDateTimeEdit):

    def wheelEvent(self, QWheelEvent):
        pass

class Contact(QWidget):

    def __init__(self,uuid):
        super(Contact, self).__init__()
        self.setWindowTitle("接触者信息")
        self.setFixedSize(350,420)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.center()
        self.db = DB()
        self.cur = self.db.cur
        self.contact_uuid = uuid
        self.register = 'hsqcdc'
        self.mark = 1
        self.update_mark = None
        self.set_ui()

    def set_ui(self):
        self.save_bnt = QPushButton("保存(F1)")
        self.save_bnt.clicked.connect(self.save_record)
        self.save_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:green;border:hidden;")
        self.new_bnt = QPushButton("添加(F2)")
        self.new_bnt.clicked.connect(self.new_record)
        self.new_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:brown;border:hidden;")
        self.close_bnt = QPushButton("关闭(ESC)")
        self.close_bnt.clicked.connect(self.close_win)
        self.close_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:red;border:hidden;")

        bnt_widget = QWidget()
        bnt_layout = QHBoxLayout()
        bnt_layout.addWidget(self.close_bnt)
        bnt_layout.addWidget(self.new_bnt)
        bnt_layout.addWidget(self.save_bnt)
        bnt_widget.setLayout(bnt_layout)

        self.uuid = QLabel()
        # self.uuid.setText(self.gen_uuid())
        self.uuid.setText(self.contact_uuid)
        self.name_label = QLabel("姓名")
        self.name = QLineEdit()
        self.name.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.id_label = QLabel("有效证件号码")
        self.id = QLineEdit()
        self.id.setPlaceholderText("身份证回车自动生成性别年龄")
        self.id.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.id.returnPressed.connect(self.id_check)
        self.gender_label = QLabel('性别')
        self.gender = QComboBox()
        self.gender.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.gender.addItem("男性")
        self.gender.addItem("女性")
        self.age_label = QLabel("年龄")
        self.age = QLineEdit()
        self.age.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.tel_label = QLabel("电话")
        self.tel = QLineEdit()
        self.tel.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.address_label = QLabel("住址")
        self.address= QLineEdit()
        self.address.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.gps_label = QLabel("职业")
        self.gps = QComboBox()
        occup_list = ['学生','教师','医务人员','冷链从业人员','幼托儿童','散居儿童','农民','干部职员','离退人员',
            '家务及待业','保姆','餐饮服务业','公共场所服务员','商业服务','工人','民工','牧民','渔船民','海员及长途驾驶员','不详','其他']
        for i in occup_list:
            self.gps.addItem(i)
        self.gps.setEditable(True)
        self.gps.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.company_label = QLabel("工作单位/学校")
        self.company = QLineEdit()
        self.company.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        # self.address_now_label = QLabel("现住地")
        # self.address_now = QLineEdit()
        # self.address_now.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        # self.gps_now_label = QLabel("现住地GPS")
        # self.gps_now = QLineEdit()
        # self.gps_now.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.backup_label = QLabel("备注")
        self.backup = QLineEdit()
        self.backup.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.status_label = QLabel("目前状态")
        self.status = QComboBox()
        self.status.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        test_list = ['健康人群','次密接','密接','无症状感染','确诊','康复']
        for i in test_list:
            self.status.addItem(i)
        self.status.setEditable(True)
        self.measure_label = QLabel("目前管理")
        self.measure = QComboBox()
        self.measure.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        test_list2 = ['无措施','居家观察','集中观察','住院']
        for i in test_list2:
            self.measure.addItem(i)
        self.measure.setEditable(True)

        self.regist_date_label = QLabel("登记日期")
        self.regist_date_label.setStyleSheet("width:60px;height:30px;color:black;background-color:None;border:hidden;")
        self.regist_date = QDateTimeEdit(QDateTime.currentDateTime())
        self.regist_date.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.regist_date_bnt = QPushButton()
        self.regist_date_bnt.setStyleSheet("border:hidden;")
        self.regist_date_bnt.setIcon(QIcon('./img/cal.ico'))
        self.regist_date_bnt.clicked.connect(lambda:self.show_dt_cal(self.regist_date))

        self.contact_date_label = QLabel("接触时间")
        self.contact_date_label.setStyleSheet("width:60px;height:30px;color:black;background-color:None;border:hidden;")
        self.contact_date = QDateTimeEdit(QDateTime.currentDateTime())
        self.contact_date.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.contact_date_bnt = QPushButton()
        self.contact_date_bnt.setStyleSheet("border:hidden;")
        self.contact_date_bnt.setIcon(QIcon('./img/cal.ico'))
        self.contact_date_bnt.clicked.connect(lambda:self.show_dt_cal(self.contact_date))

        self.relationship_label = QLabel("人物关系")
        self.relationship_label.setStyleSheet("width:60px;height:30px;color:black;background-color:None;border:hidden;")
        self.relationship = QLineEdit()
        self.relationship.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")

        self.contact_level_label = QLabel("接触级别")
        contact_level_list = ['一般接触','密接接触']
        self.contact_level = QComboBox()
        for i in contact_level_list:
            self.contact_level.addItem(i)
        self.contact_level.setEditable(True)
        self.contact_level.setCurrentIndex(0)
        self.contact_level_label.setStyleSheet("width:60px;height:30px;color:black;background-color:None;border:hidden;")
        self.contact_level.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")

        self.contact_place_lable = QLabel("接触地点")
        self.contact_place = QLineEdit()
        self.contact_place_lable.setStyleSheet("width:60px;height:30px;color:black;background-color:None;border:hidden;")
        self.contact_place.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")

        self.bnt_layout = QHBoxLayout()
        self.bnt_layout2 = QWidget()
        self.bnt_layout.addWidget(self.close_bnt)
        self.bnt_layout.addWidget(self.new_bnt)
        # self.bnt_layout.addWidget(self.update_bnt)
        self.bnt_layout.addWidget(self.save_bnt)
        self.bnt_layout2.setLayout(self.bnt_layout)

        self.info_layout = QGridLayout()
        self.info_layout2 = QWidget()
        widget_list = [self.regist_date_label,self.regist_date,self.name_label,
                    self.name,self.id_label,self.id,self.gender_label,self.gender,
                    self.age_label,self.age,self.tel_label,self.tel,self.address_label,self.address,
                    self.gps_label,self.gps,self.company_label,self.company,
                    self.status_label,self.status,
                    self.measure_label,self.measure,self.backup_label,self.backup,
                    self.contact_date_label,self.contact_date,self.contact_level_label,
                    self.contact_level,self.contact_place_lable,self.contact_place,
                    self.relationship_label,self.relationship]
        for i in range(15):
            self.info_layout.addWidget(widget_list[i*2],i,0)
            self.info_layout.addWidget(widget_list[i*2+1],i,1)
        self.info_layout.addWidget(self.regist_date_bnt,0,2)
        self.info_layout.addWidget(self.contact_date_bnt,11,2)

        self.info_layout2.setLayout(self.info_layout)

        self.scroll = QScrollArea(self)
        self.scroll.setStyleSheet('border:None;')
        self.scroll.setAutoFillBackground(True)
        self.scroll.setMinimumSize(300,320)
        self.scroll.setWidgetResizable(True)
        self.scroll_bar = self.scroll.verticalScrollBar()

        self.scroll.setWidget(self.info_layout2)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.scroll)
        self.main_layout.addWidget(self.bnt_layout2)
        self.main_layout.addWidget(self.uuid)
        self.setLayout(self.main_layout)


    def save_record(self):
        try:
            age = int(self.age.text())
        except:
            age = 0
        data_dic = {
        'name':self.name.text(),
        'id':self.id.text().upper(),
        'gender':self.gender.currentText(),
        'age':age,
        'tel':self.tel.text(),
        'address':self.address.text(),
        'occup':self.gps.currentTextext(),
        'company':self.company.text(),
        'status':self.status.currentText(),
        'measure':self.measure.currentText(),
        'backup':self.backup.text(),
        'uuid':self.uuid.text(),
        'register':self.register,
        'date':self.change_datetime(self.regist_date),
        'contact_date':self.change_datetime(self.contact_date),
        'contact_level':self.contact_level.currentText(),
        'contact_place':self.contact_place.text(),
        'relationship':self.relationship.text(),
        'contact_uuid':self.contact_uuid
        }
        try:
            person_sql = ''' insert into person values (null,"{uuid}",
            "{name}","{id}","{gender}",{age},"{tel}",'{address}',
            "{occup}","{company}",{date},"{status}","{measure}",
            '{backup}',"{register}",0
            )
            '''.format(**data_dic)
            self.cur.execute(person_sql)
        except:
            person_sql = ''' update person set name =
            "{name}",id = "{id}",gender = "{gender}", age = {age},
            tel= "{tel}",address = '{address}',
            occup = "{occup}",company = "{company}",backup= '{backup}',regist_date = {date},
            present_status = "{status}", present_measure =
            "{measure}" where uuid = "{uuid}"
            '''.format(**data_dic)
            self.cur.execute(person_sql)
        try:
            contact_sql = '''insert into relation values(
            null,"{uuid}","{contact_uuid}",{contact_date},"{contact_level}",
            null,"{contact_place}","{relationship}"
            )
            '''.format(**data_dic)
            self.cur.execute(contact_sql)
        except:
            contact_sql = '''update relation set
            contact_date = {contact_date},contact_level = "{contact_level}",
            contact_place = "{contact_place}",relationship = "{relationship}"
            where uuid = "{uuid}" and contact_uuid = "{contact_uuid}"
            )
            '''.format(**data_dic)
            self.cur.execute(contact_sql)
        self.db.con.commit()

    def update_record(self):
        pass

    def new_record(self):
        # widget_list = [self.name,self.id,self.gender,
        #     self.age,self.tel,self.address,
        #     self.gps,self.status,self.measure,self.backup]
        # for i in widget_list:
        #     i.clear()
        # self.uuid.setText(self.gen_uuid())
        # self.save_bnt.setText("保存(F1)")
        self.close()
        if self.win:
            self.win.close()
        self.win = Contact(self.contact_uuid)
        self.win.show()

    def close_win(self):
        self.db.con.close()
        self.close()

    def show_dt_cal(self, tmp):#含时间日历控件
        self.cal = Calendar_With_Clock(tmp)
        self.cal.show()
        self.cal.datetime_signal.connect(self.input_deathday)

    def input_deathday(self, list):
        list[0].setDateTime(list[1])

    def change_datetime(self,pyqtdatetime):   # a pyqtdate style /yyyymmdd to time stamp
        pydate = pyqtdatetime.dateTime().toPyDateTime()
        base_date = datetime.datetime(1970,1,1,0,0)
        day_delta = pydate - base_date
        days = day_delta.days
        seconds = day_delta.seconds
        seconds += days*24*3600
        return seconds

    def gen_uuid(self):
        return (str(uuid.uuid1()))

    def id_check(self):
        id_upper = self.id.text().upper().strip()
        sql = '''select * from person where id = "{}"
        '''.format(id_upper)
        try:
            self.cur.execute(sql)
            check_rslt = self.cur.fetchone()
        except:
            QMessageBox.information(self,'tips','证件号格式有误',QMessageBox.Yes,QMessageBox.Yes)
        if check_rslt:
            msg = QMessageBox.information(self,'tips','有相同证件,是否更新原纪录YES或重新登记NO',QMessageBox.Yes,QMessageBox.No)
            if msg == QMessageBox.Yes:
                self.uuid.setText(check_rslt[1])
            else:
                self.uuid.setText(self.gen_uuid())
            self.name.setText(check_rslt[2])
            self.tel.setText(check_rslt[6])
            self.address.setText(check_rslt[7])
            self.occup.setCurrentText(check_rslt[8])
            self.regist_date.setDateTime(self.to_pydatetime(check_rslt[10]))
            self.status.setCurrentText(check_rslt[11])
            self.measure.setCurrentText(check_rslt[12])
            self.backup.setText(check_rslt[13])

        if len(id_upper) == 18:
            try:
                certify_number = ['1','0','X','9','8','7','6','5','4','3','2']
                std_number = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
                sum = 0
                for i in range(17):
                    sum += int(id_upper[i])*std_number[i]
                certify_rslt = certify_number[sum%11]
                if certify_rslt == id_upper[-1]:
                    self.id.setText(id_upper)
                    year2 = int(id_upper[6:10])
                    month2 = int(id_upper[10:12])
                    day2 = int(id_upper[12:14])
                    now = (datetime.datetime.now() + datetime.timedelta(days=1))
                    year = now.year
                    month = now.month
                    day = now.day
                    if year == year2:
                        self.age.setText('1')
                    else:
                        if month > month2 or (month == month2 and day > day2 ):
                            self.age.setText(str(year-year2))
                        else:
                            self.age.setText(str(year-year2-1))

                    sex = int(id_upper[-2])
                    if sex%2==0:
                        self.gender.setCurrentIndex(1)
                    else:
                        self.gender.setCurrentIndex(0)
                    self.tel.setFocus()
                    self.id.setStyleSheet('color:black;')
                else:
                    self.id.setStyleSheet('color:red;')
                    # QMessageBox.information(self,'提示','身份证号码不正确',QMessageBox.Yes, QMessageBox.Yes)
            except:
                self.id.setStyleSheet('color:red;')
        else:
            self.id.setStyleSheet('color:red;')
            # QMessageBox.information(self,'提示','身份证号码不满18位',QMessageBox.Yes, QMessageBox.Yes)
        self.tel.setFocus()


    def to_pydatetime(self, a):
        b = datetime.datetime(1970, 1, 1, 0, 0) + datetime.timedelta(seconds=a)
        return QDateTime(b.year, b.month, b.day, b.hour, b.minute)

    def center(self):
        self.screen = QDesktopWidget().screenGeometry()
        self.size = self.geometry()
        self.move(int((self.screen.width()-self.size.width())/2),
                 int((self.screen.height()-self.size.height())/2)
                  )

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Escape:
            self.close_win()
        if e.key() == Qt.Key_F1:
            self.save_record()
        if e.key() == Qt.Key_F2:
            self.new_record()

class Contact_List(QWidget):

    def __init__(self,uuid):
        super(Contact_List,self).__init__()
        self.contact_uuid = uuid
        self.setWindowTitle("密切接触者一览表")
        self.setFixedSize(900,500)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.center()
        self.win = None
        self.db = DB()
        self.cur = self.db.cur
        self.set_ui()

    def set_ui(self):

        new_bnt = QPushButton("新增")
        new_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:green;border:hidden;")
        new_bnt.clicked.connect(self.add_new)
        self.close_bnt = QPushButton("关闭(ESC)")
        self.close_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:red;border:hidden;")
        self.close_bnt.clicked.connect(self.close_win)
        export_bnt = QPushButton("导出")
        export_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:blue;border:hidden;")
        export_bnt.clicked.connect(self.export)
        vacci_bnt = QPushButton("疫苗接种史")
        vacci_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:blue;border:hidden;")
        vacci_bnt.clicked.connect(self.vacci)
        bnt_widget = QWidget()
        bnt_layout = QHBoxLayout()
        bnt_layout.addWidget(new_bnt)
        bnt_layout.addWidget(export_bnt)
        bnt_layout.addWidget(vacci_bnt)
        bnt_layout.addWidget(self.close_bnt)
        bnt_widget.setLayout(bnt_layout)

        self.table = QTableWidget(15,10)
        # self.table.setShowGrid(False)
        # self.table.setFrameShape(QFrame.NoFrame)
        # self.table.setStyleSheet('background:transparent;')

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        layout.addWidget(bnt_widget)
        self.setLayout(layout)

    def refresh_table(self):
        self.table.clear()
        self.table.setHorizontalHeaderLabels(['操作','姓名','关系','电话','地址','接触日期','接触地点','接触级别','现状','管理'])
        self.db2 = DB()
        self.cur2 = self.db2.cur
        sql = '''select person.name,relation.relationship,person.tel,person.address,
            relation.contact_date,relation.contact_place,relation.contact_level,
            person.present_status,person.present_measure,person.uuid
            from person,relation
            '''

        sql_contact = sql+ '''where person.uuid  = relation.uuid and
            relation.contact_uuid = "{}" order by person.present_status
        '''.format(self.contact_uuid)
        self.cur2.execute(sql_contact)
        rslt = self.cur2.fetchall()
        sql_patient = sql+ ''' where person.uuid  = relation.contact_uuid and
            relation.uuid = "{}" order by person.present_status
        '''.format(self.contact_uuid)
        self.cur2.execute(sql_patient)
        rslt += self.cur2.fetchall()
        rslt = set(rslt)
        k = 0

        color_list = ["#00FF00","#4682b4","#996633","#DC143c","#DC1400","#FF0000","#008800","#4b0082"]
        status_list = ['健康人群','一般接触者','密接','初筛阳性','无症状感染','确诊','康复','死亡']
        count = len(rslt)
        if not count:
            count = 10
        self.table.setRowCount(count)
        if rslt:
            for i in rslt:
                for j in range(8):
                    if i[j]:
                        str_ij = str(i[j])
                    else:
                        str_ij = '-'
                    item_tmp = QTableWidgetItem(str_ij)
                    item_tmp.setTextAlignment(Qt.AlignCenter)
                    self.table.setItem(k,j+1,item_tmp)
                    try:
                        color = color_list[status_list.index(i[7])]
                    except:
                        color = Qt.black
                    # print(i[7],color)
                    self.table.item(k,j+1).setForeground(QColor(color))

                self.table.setCellWidget(k,0,self.button_row(i[-1]))
                k += 1
        self.db2.con.close()


    def button_row(self, tmp_uuid):
        self.widget = QWidget()
        self.view_bnt = QPushButton('查看')
        self.del_bnt = QPushButton('删除')

        self.view_bnt.setStyleSheet('''text-align:center; background-color:green;border-style:outset;height:20px;color:white;''')
        self.del_bnt.setStyleSheet('''text-align:center;background-color: red;border-style:outset;height:20px;color:white;''')

        self.hlayout = QHBoxLayout()

        self.hlayout.addWidget(self.view_bnt)
        self.hlayout.addWidget(self.del_bnt)
        self.hlayout.setContentsMargins(5,2,5,2)

        self.view_bnt.clicked.connect(lambda:self.view_record(tmp_uuid))
        self.del_bnt.clicked.connect(lambda:self.del_record(tmp_uuid))
        self.widget.setLayout(self.hlayout)
        return self.widget

    def export(self):
        sql = ''' SELECT person1.name AS patient_name,person1.id AS id2,
            	person2.name,relation.relationship,person2.id,
                person2.gender,person2.age,person2.occup,person2.tel,person2.address,
                relation.contact_place,relation.contact_date,relation.contact_level,
                relation.contact_freq,person2.present_measure
            FROM
            	relation,
            	person AS person1,
            	person AS person2
            WHERE
            	relation.contact_uuid = person1.uuid
            	AND relation.uuid = person2.uuid
            	AND (relation.contact_uuid = "{}" or relation.uuid = "{}")
            '''.format(self.contact_uuid,self.contact_uuid)
        self.cur.execute(sql)
        rslt = self.cur.fetchall()
        if rslt:
            self.export_xls(rslt,rslt[0][0])

    def export_xls(self,rslt,label='tmp'):
        if rslt:
            workbook = xlwt.Workbook(encoding='utf-8')
            sheet = workbook.add_sheet("Sheet1")
            head = ['序号', '重点人群','病例姓名','病例身份证号码','密接姓名',
                     '关系','身份证号','性别','年龄','职业','联系电话','现住址',
                    '接触地点','末次接触时间','接触方式','接触频率','防护情况',
                    '是否外地','是否需要协查','管控措施','解除隔离日期','备注']
            cols = len(head)
            rows = len(rslt)
            for col in range(cols):
                sheet.write(0,col,head[col])
            for i in range(rows):
                rslti = rslt[i]
                tmp = ['','',]
                tmp += [k for k in rslti][0:11]
                tmp += [self.to_xls_date(rslti[11]),]
                tmp += [rslti[12],rslti[13],'','','',rslti[14],'','']
                for col in range(cols):
                    sheet.write(i+1,col,tmp[col])
            filename,ok = QFileDialog.getSaveFileName(self,'保存结果文件','{}密接一览表.xls'.format(label),'Excel Files (*.xls)')
            if filename:
                workbook.save(filename)
                self.messagebox_auto_close("保存成功")

    def vacci(self):
        sql = '''select * from vaccine where id = "{}"'''.format(self.contact_uuid)
        self.cur.execute(sql)
        rslt = self.cur.fetchone()
        if rslt:
            if self.win:
                self.win.close()
            self.win = Vacci(rslt)
            self.win.show()

    def to_xls_date(self,t):
        a = datetime.datetime(1970,1,1) + datetime.timedelta(seconds=t)
        b = a.strftime('%Y-%m-%d')
        return b

    def messagebox_auto_close(self,txt = '完成!!!',time =1):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setWindowTitle("# WARNING: ")
        msg.setText(txt)
        msg.setStandardButtons(QMessageBox.Yes)
        msg.button(QMessageBox.Yes).animateClick(time*1000)
        msg.exec_()

    def view_record(self,tmp_uuid):
        if self.win:
            self.win.close()
        self.win = Contact(tmp_uuid)
        self.win.contact_uuid = self.contact_uuid
        self.cur.execute('select * from person where uuid = "{}"'.format(tmp_uuid))
        person_rslt = self.cur.fetchone()
        # self.cur.execute('select regist_date,present_status,present_measure from cases where uuid = "{}"'.format(tmp_uuid))
        # case_rslt = self.cur.fetchone()
        self.cur.execute('select contact_date,contact_level,contact_place,relationship from relation where uuid = "{}" and contact_uuid = "{}"'.format(tmp_uuid,self.contact_uuid))
        contact_rslt = self.cur.fetchone()
        self.win.uuid.setText(person_rslt[1])
        self.win.name.setText(person_rslt[2])
        self.win.id.setText(person_rslt[3])
        self.win.gender.setCurrentText(person_rslt[4])
        self.win.age.setText(str(person_rslt[5]))
        self.win.tel.setText(person_rslt[6])
        self.win.address.setText(person_rslt[7])
        self.win.gps.setText(person_rslt[8])
        self.win.regist_date.setDateTime(self.to_pydatetime(person_rslt[9]))
        self.win.status.setCurrentText(person_rslt[10])
        self.win.measure.setCurrentText(person_rslt[11])
        self.win.contact_date.setDateTime(self.to_pydatetime(contact_rslt[0]))
        self.win.contact_level.setCurrentText(contact_rslt[1])
        self.win.contact_place.setText(contact_rslt[2])
        self.win.relationship.setText(contact_rslt[3])
        self.win.show()
        self.win.new_bnt.setVisible(False)
        self.win.close_bnt.clicked.connect(self.refresh)


    def del_record(self,tmp_uuid):
        sql = '''delete from relation where uuid = "{}" and contact_uuid = "{}"
        '''.format(tmp_uuid,self.contact_uuid)
        msg = QMessageBox.warning(self,'tips','是否删除',QMessageBox.Yes,QMessageBox.No)
        if msg == QMessageBox.Yes:
            self.cur.execute(sql)
            self.db.con.commit()
            self.refresh()

    def to_date(self,a):
        b = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=a)
        c = b.strftime('%m/%d %H:%M')
        return c

    def to_pydatetime(self, a):
        b = datetime.datetime(1970, 1, 1, 0, 0) + datetime.timedelta(seconds=a)
        return QDateTime(b.year, b.month, b.day, b.hour, b.minute)

    def close_win(self):
        self.db.con.close()
        self.close()

    def refresh(self):
        self.refresh_table()

    def add_new(self):
        if self.win:
            self.win.close()
        self.win = Contact(self.contact_uuid)
        self.win.show()
        self.win.name.setFocus()
        self.win.close_bnt.clicked.connect(self.refresh)

    def center(self):
        self.screen = QDesktopWidget().screenGeometry()
        self.size = self.geometry()
        self.move(int((self.screen.width()-self.size.width())/2),
                 int((self.screen.height()-self.size.height())/2)
                  )

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Escape:
            self.close_win()


class Vacci(QWidget):

    def __init__(self,rslt):
        super(Vacci,self).__init__()
        self.rslt = rslt
        print(self.rslt)
        self.setFixedSize(360,310)
        self.center()
        self.set_ui()

    def set_ui(self):

        name = QLineEdit(self.rslt[1])
        name.setReadOnly(True)
        id = QLineEdit(self.rslt[0])
        id.setReadOnly(True)
        name.setStyleSheet('background-color:None;color:black;border:hidden;width:120px;height:30px')
        id.setStyleSheet('background-color:None;color:black;border:hidden;width:120px;height:30px')
        self.table = QTableWidget(6,3)
        self.table.setHorizontalHeaderLabels(['针次','接种日期','疫苗品牌'])
        name_list = ['第一剂','第二剂','第三剂','加强针1','加强针2','加强针3']
        for i in range(6):
            self.table.setItem(i,0,QTableWidgetItem(name_list[i]))
        dose_list = [self.rslt[i] for i in range(3,15)]
        k = 0
        for i in range(12):
            if not i%2:
                dose_list[i]= self.to_xls_date(dose_list[i])
            tmp = QTableWidgetItem(dose_list[i])
            self.table.setItem(k,i%2+1,tmp)
            k +=  i%2

        bnt = QPushButton('关闭')
        bnt.clicked.connect(lambda:self.close())
        bnt.setStyleSheet('height:30px;border:solid;color:white;background:#FF0000')

        layout = QGridLayout()
        layout.addWidget(name,0,0)
        layout.addWidget(id,0,1)
        layout.addWidget(self.table,1,0,5,2)
        layout.addWidget(bnt,6,0,1,2)
        self.setLayout(layout)


    def to_xls_date(self,t):
        if t > 1000000:
            a = datetime.datetime(1970,1,1) + datetime.timedelta(seconds=t)
            b = a.strftime('%Y-%m-%d')
        else:
            b = ''
        return b

    def center(self):
        self.screen = QDesktopWidget().screenGeometry()
        self.size = self.geometry()
        self.move(int((self.screen.width()-self.size.width())/2),
                 int((self.screen.height()-self.size.height())/2)
                  )

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Escape:
            self.close()
